<template>
  <section style="margin-left: 24px">
    <section>
      <pre>
        {{ personnelList }}
      </pre>
    </section>
    <section class="flex flex-jc-start" style="margin-bottom: 24px">
      <el-button type="primary" @click="changeTableType('add')">添加</el-button>
      <el-button
        type="primary"
        :disabled="!editIndex"
        @click="changeTableType('edit')"
      >
        编辑
      </el-button>
      <el-button @click="returnTableData">查看</el-button>
    </section>
    <pre>
      <!-- {{ JSON.parse() }} -->
    </pre>
    <section v-if="formType">
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="日期">
          <el-date-picker
            v-model="form.date"
            type="date"
            placeholder="Pick a date"
            clearable
          />
        </el-form-item>
        <el-form-item label="名字">
          <el-input aria-autocomplete="none" v-model="form.name" />
        </el-form-item>
        <el-form-item label="对手名字">
          <el-input aria-autocomplete="none" v-model="form.nameBattle" />
        </el-form-item>
        <el-form-item label="对手排序">
          <el-input aria-autocomplete="none" v-model="form.indexBattle" />
        </el-form-item>
        <el-form-item label="星星">
          <el-input aria-autocomplete="none" v-model="form.star" />
        </el-form-item>
        <el-form-item label="摧毁度">
          <el-input aria-autocomplete="none" v-model="form.percentage" />
        </el-form-item>
        <el-form-item label="大本营">
          <el-input aria-autocomplete="none" v-model="form.lv" />
        </el-form-item>
        <el-form-item label="对战大本营">
          <el-input aria-autocomplete="none" v-model="form.lvBattle" />
        </el-form-item>
        <el-form-item label="对战匹配值">
          <el-input aria-autocomplete="none" v-model="form.matchingValue" />
        </el-form-item>
        <el-form-item label="思路评分">
          <el-input aria-autocomplete="none" v-model="form.thinkingScore" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="editConfirm">确认修改</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </section>
    <section v-else>
      <el-input v-model="pagination.name" @change="getTableData"></el-input>
      <el-table
        highlight-current-row
        :data="tableData"
        style="width: 100%"
        @current-change="handleCurrentChange"
      >
        <!-- <el-table-column type="expand">
        <template #default="props">
          <div m="4">
            <pre>
              {{ props }}
            </pre>
          </div>
        </template>
      </el-table-column> -->
        <el-table-column label="日期">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{
                moment(scope.row.date).format('MM-DD')
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="名字">
          <template #default="scope">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="scope.row.name"
              placement="left-start"
            >
              <div class="jt-text-overflow-hidden-1">
                {{ scope.row.name }}
              </div></el-tooltip
            >
          </template>
        </el-table-column>
        <el-table-column label="星星" prop="star" />
        <el-table-column label="摧毁度" prop="percentage" />
        <el-table-column label="大本营" prop="lv" />
        <el-table-column label="对战大本营" prop="lvBattle" />
        <el-table-column label="对战匹配值" prop="matchingValue" />
        <el-table-column label="思路评分" prop="thinkingScore" />
      </el-table>
      <div class="example-pagination-block">
        <el-pagination
          v-model:current-page="pagination['current-page']"
          v-model:page-size="pagination['page-size']"
          layout="prev, pager, next"
          :total="pagination.total"
          @change="getTableData"
        />
      </div>
    </section>
  </section>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import moment from 'moment';
import { cloneDeep } from '@/utils/metheds';
import { TableData, data, battleData, nameList } from './data/score';

const editIndex = ref();

const formType = ref();

const personnelList: any = reactive([]);

const pagination = reactive({
  total: 0,
  'page-size': 10,
  'current-page': 1,
  name: '',
});

const sqlData: Array<TableData> = cloneDeep(data);

const tableData: Array<TableData> = reactive(cloneDeep(sqlData));

const form: TableData = reactive({
  id: '',
  date: '',
  name: '',
  star: 0,
  lv: 0,
  percentage: 0,
  thinkingScore: 0,
  lvBattle: 0,
  matchingValue: 0,
  nameBattle: '',
  indexBattle: 0,
});

// 选中表格行
function handleCurrentChange(val: TableData) {
  if (!val) return;
  const i = sqlData.findIndex((item) => item.id === val.id);
  editIndex.value = i + '';
  for (const key in form) {
    form[key] = sqlData[i][key];
  }
}

// 修改提交
function editConfirm() {
  const datetime = (+new Date()).toString();
  const random = Math.floor(Math.random() * 12);
  if (!form.id)
    form.id =
      datetime.slice(0, random) +
      'id' +
      datetime.slice(random, datetime.length);
  for (const key in form) {
    if (!isNaN(+form[key]) && key !== 'name' && key !== 'nameBattle') {
      form[key] = +form[key];
    }
  }

  switch (formType.value) {
    case 'add':
      sqlData.push(cloneDeep(form));
      break;
    case 'edit':
      sqlData.splice(+editIndex.value, 1, cloneDeep(form));
      break;

    default:
      break;
  }
  getTableData();
  cancel();
}

getTableData();
// 清空form 表单
function formClear() {
  for (const key in form) {
    const type = Object.prototype.toString.call(form[key]);
    switch (type) {
      case '[object String]':
        form[key] = '';
        break;
      case '[object Number]':
        form[key] = 0;
        break;
      //   case '[object String]':
      //     break;
      //   case '[object String]':
      //     break;

      default:
        break;
    }
  }
}

// 添加 | 编辑
function changeTableType(type: string) {
  if (type === 'add') {
    form.id = '';
    formClear();
    form.date = '2024-04-26';
  }
  formType.value = type;
}

// 查看
function returnTableData() {
  const data = JSON.stringify(
    sqlData.filter((item) => item.date === '2024-04-26'),
  );
  console.log(data);
  window.localStorage.setItem('scoreCoc', data);
}

// 取消编辑
function cancel() {
  formType.value = undefined;
  editIndex.value = undefined;
  formClear();
}

interface Param {
  pageSize: number;
  currentPage: number;
  name: string;
}

// 获取表格信息
function getTableData() {
  formClear();
  formType.value = '';
  editIndex.value = null;
  tableData.splice(0, tableData.length);
  const param: Param = {
    pageSize: pagination['page-size'],
    currentPage: pagination['current-page'],
    name: pagination.name,
  };
  // const nameList: any = [];
  const temp = sqlData.map((item) => {
    const res = getRepeatBattle(item);
    // console.log(res);
    // if (!nameList.find((val: any) => val.name === item.name))
    //   nameList.push({ name: item.name });

    return {
      ...res,
      percentage: item.star == 3 ? 100 : item.percentage,
    };
  });
  // console.log(JSON.stringify(nameList));
  console.log(temp);
  sqlData.splice(0, sqlData.length, ...temp);
  const { pageSize, currentPage, name } = param;
  const searchData = sqlData.filter((item) => !name || item.name === name);
  const data = searchData.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize,
  );
  pagination.total = searchData.length;
  tableData.push(...cloneDeep(data));
}

/**
 * 对手名字、序列一致 则 匹配值、大本营等级一致
 * @param val 比较的对象
 * @param arr 所有的对手数组
 * @return 同化完以后的对象
 */
function getRepeatBattle(val: TableData) {
  const res = cloneDeep(val);
  cloneDeep(battleData).forEach((item: any) => {
    if (
      moment(item.date).format('MM-DD') === moment(val.date).format('MM-DD')
    ) {
      item.data.forEach((item: any) => {
        if (item.index === val.indexBattle) {
          res.lvBattle = item.lv;
          res.matchingValue = item.matchingValue;
          res.nameBattle = item.name;
        }
      });
    }
  });
  return res;
}
getScore();
function getScore() {
  // 人员名单
  const scoreList = cloneDeep(nameList);
  // 历史战绩
  const history = cloneDeep(sqlData);
  // 过滤人员
  const passList: Array<string> = [];
  history.forEach((item: TableData) => {
    const scoreIndex = scoreList.findIndex(
      (val: any) => val.name === item.name,
    );
    // 过滤 pass 名单内人员
    if (passList.includes(item.name)) return;
    const i = scoreList.findIndex((val: any) => val.name === item.name);
    if (item.lvBattle == 0) {
      // 没打 -5分
      scoreList[i].pass = scoreList[i].pass ? scoreList[i].pass + 1 : 1;
      scoreList[i].score -= 5;
      // 没打达到4次 列入pass名单
      if (scoreList[i].pass >= 4) {
        passList.push(item.name);
      }
    } else if (item.lv === item.lvBattle) {
      // 同本 3星 + 10分
      if (item.star === 3) {
        if (item.matchingValue < 640) {
          scoreList[i].score += 10;
        } else {
          scoreList[i].score += 15;
        }
      }
      // 同本 2星 + 5 ~ 8分
      if (item.star === 2) {
        // percentage 50 ~ 99    0 1 2 3
        if (item.name === '路飞' && item.percentage == 78) {
          const res = getAdditional(
            item.percentage,
            0,
            3,
            50,
            99,
            [75, 90, 95, 99],
          );
          scoreList[i].score += +(res + 5).toFixed(2);
        }
      }
      // // 同本 1星 - 0 ~ 5分
      if (item.star === 1) {
        const res = getAdditional(
          item.percentage,
          5,
          0,
          50,
          99,
          [50, 70, 85, 90],
        );
        // console.log(item.name, scoreList[i].score - res);
        scoreList[i].score = +(scoreList[i].score - res).toFixed(2);
      }
      // 同本 黑3 - 20分
      if (item.star === 0) scoreList[i].score -= 20;
    } else if (item.lv > item.lvBattle) {
      // 低本 3星 + 5分
      if (item.star === 3) scoreList[i].score += 5;
      // 低本 2星 - 5 ~ 10分
      if (item.star === 2) {
        const res = getAdditional(
          item.percentage,
          5,
          0,
          50,
          99,
          [75, 90, 95, 99],
        );
        scoreList[i].score = +(scoreList[i].score - res - 5).toFixed(2);
      }
      // 低本 1星 - 20分
      if (item.star === 1) scoreList[i].score -= 20;
      // 低本 黑三 pass
      if (item.star === 0) scoreList[i].pass += 4;
    } else if (item.lv < item.lvBattle) {
      // 越本 3星 + 20分
      if (item.star === 3) {
        if (item.matchingValue < 640) {
          scoreList[i].score += 20;
        } else {
          scoreList[i].score += 30;
        }
      }
      // 越本 2星 + 5 ~ 15分
      if (item.star === 2) {
        const res = getAdditional(
          item.percentage,
          5,
          0,
          50,
          99,
          [80, 90, 95, 99],
        );
        scoreList[i].score += +res.toFixed(2) - 5;
      }
      // 越本 1星 - 5分
      if (item.star === 1) scoreList[i].score -= 5;
      // 越本 黑3 - 15分
      if (item.star === 0) scoreList[i].score -= 15;
    }
  });
  for (let i = 0; i < scoreList.length; i++) {
    if (scoreList[i].lv > 13) {
      scoreList[i].score += scoreList[i].lv * 3;
    } else if (scoreList[i].lv > 14) {
      scoreList[i].score += scoreList[i].lv * 5;
    }
  }
  scoreList.sort((a: any, b: any) => b.score - a.score);
  const list = scoreList.filter((item: any) => item.pass < 4 || !item.pass);
  console.log(
    list,
    scoreList.filter((item: any) => item.pass >= 4),
  );
  personnelList.push(...list.slice(0, 27).map((item) => item.name));
}
/**
 * 获取波动分值
 * @param percentage 进攻比例
 * @param min 波动最小值 用于扣分计算时 min 跟 max 换个位置
 * @param max 波动最大值
 * @param start 起始比例
 * @param end 最大比例
 * @param gradualNode 渐变节点
 */
function getAdditional(
  percentage: number,
  min: number,
  max: number,
  start: number,
  end: number,
  gradualNode: false | Array<number> = false,
) {
  const isAdd = max - min > 0;
  let res = max - min;
  const averageVal =
    (isAdd ? max : min) / (gradualNode ? gradualNode.length : end);
  if (gradualNode) {
    const sortNode = cloneDeep(gradualNode);
    if (isAdd) sortNode.sort((a: number, b: number) => a - b);
    if (!isAdd) sortNode.sort((a: number, b: number) => b - a);
    for (let i = 0; i < sortNode.length; i++) {
      if (percentage > sortNode[i] && isAdd) {
        if (i + 1 >= sortNode.length) res = max;
        continue;
      } else if (percentage < sortNode[i] && !isAdd) {
        if (i + 1 >= sortNode.length) res = min;
        continue;
      } else {
        if (isAdd) {
          res = averageVal * i;
          // [75, 90, 95, 99]  92
          if (percentage != sortNode[i] && i > 0) {
            const r = averageVal / (sortNode[i] - sortNode[i - 1]);
            res += r * (percentage - sortNode[i]);
          }
        } else {
          res = averageVal * i;
          if (percentage != sortNode[i]) {
            const r = averageVal / (sortNode[i - 1] - sortNode[i]);
            res += r * (percentage - sortNode[i]);
          }
        }
        break;
      }
    }
  } else {
    res = averageVal * (end - start);
  }

  return res;
}
</script>
